package top.itaso.app.ui.floating;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import top.itaso.app.R;
import top.itaso.lib.alog.ALog;

/**
 * @Description:
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Github https://github.com/itsdf07
 * @Date 2022/02/08
 */
public class FloatingWindowService extends Service {
    private static final String TAG = "FloatingWindowService";
    private WindowManager mWindowManager;
    private FloatingWindowView mFloatingWindowView;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        ALog.dTag(TAG, "intent=%s", intent);
        return null;
    }

    @Override
    public void onCreate() {
        ALog.dTag(TAG, "......");
        mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        if (mFloatingWindowView == null) {
            mFloatingWindowView = new FloatingWindowView(this);
            mFloatingWindowView.refreshUI("依附Service的悬浮窗");
        }
        mWindowManager.addView(mFloatingWindowView, mFloatingWindowView.getFloatingWindowLayoutParams());
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int sticky = super.onStartCommand(intent, flags, startId);
        ALog.dTag(TAG, "flags=%s,startId=%s,sticky=%s", flags, startId, sticky);
        return sticky;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        ALog.dTag(TAG, "startId=%s", startId);
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        ALog.dTag(TAG, "......");
        super.onDestroy();
        if (mWindowManager != null) {
            if (mFloatingWindowView != null && mFloatingWindowView.isAttachedToWindow()) {
                mWindowManager.removeView(mFloatingWindowView);
            }
            mWindowManager = null;
        }
    }
}
